import merge from "webpack-merge";
import TerserWebpackPlugin from "terser-webpack-plugin";
import { Configuration, Stats, webpack } from "webpack";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import { CleanWebpackPlugin } from "clean-webpack-plugin";
import { resolveApp } from "./path";
import CopyWebpackPlugin from "copy-webpack-plugin";

import { getWebPackCommonConfig } from "./webpack.common";
import { getProjectName } from "./webpack.utils";

const commoneConfig = getWebPackCommonConfig("production");

const name = getProjectName();

function getWebPackProductionConfig(): Configuration {
  return merge(commoneConfig, {
    //输出这样为了方便以后做微前端
    output: {
      clean: true,
      path: resolveApp("./dist"),
      filename: "js/[name].bundle.js",
      chunkFilename: "js/[name].chunk.js",
      publicPath: "/",
      library: `${name}-[name]`,
      libraryTarget: "umd",
      chunkLoadingGlobal: `webpackJsonp_${name}`,
    },

    plugins: [
      new CleanWebpackPlugin(),
      new MiniCssExtractPlugin({
        filename: "css/[name]-[contenthash:8].css",
      }),

      new CopyWebpackPlugin({
        patterns: [
          {
            from: resolveApp("public"),
            to: resolveApp("dist"),
          },
        ],
      }),
    ],

    optimization: {
      runtimeChunk: true, // 模块抽取，利用浏览器缓存
      minimizer: [
        new TerserWebpackPlugin({
          extractComments: false, // 不要注释生成的文件
        }),
      ],
    },
  });
}

const webpackConfig = getWebPackProductionConfig();

// console.log("webpack 配置如下");
// console.log(webpackConfig);

const compiler = webpack(webpackConfig);

compiler.run((err: null | Error, stats?: Stats) => {
  if (err) {
    throw err;
  }

  if (stats) {
    process.stdout.write(
      stats.toString({
        colors: true,
      }),
    );
    process.stdout.write("\n");
  }
});
